<script setup lang="ts">
import {useUserStore} from "@/store/user";
import {onMounted, reactive, ref, watch, watchEffect} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useIndexStore} from "@/store/main";
import {storeToRefs} from "pinia";

const indexStore = useIndexStore()
// 是否登录，用于样式切换
const is_login = ref(true)
// 用户状态
const userStore = useUserStore()
// 路由实例
const router = useRouter()
// 按钮状态
const btn = ref(true)

const rules = reactive({
  account: [
    {required: true, message: '请输入账户', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
  ],
})

// 侦听账户和密码，不为空时激活按钮
watchEffect(() => {
  btn.value = !(userStore.user.account && userStore.user.password);
})

onMounted(() => {
  userStore.local_user = JSON.parse(localStorage.getItem('local_user') || '[]')
})
// 根据本地账户更改头像
const getAvatar = () => {
  for (let user of userStore.local_user) {
    if (String(user.account) === userStore.user.account) {
      userStore.user.avatar = user.avatar;
      break; // 找到匹配项后立即退出循环
    } else {
      userStore.user.avatar = '';
    }
  }
}
// 登录
const on_login = async () => {
  const [is_add, data] = await userStore.on_login()
  localStorage.setItem('user', JSON.stringify(data))
  console.log(is_add);
  
  if (is_add) {
    userStore.set_user(data)
    await userStore.get_show_message_list()

    // 如果用户存在则不进行push
    if (!userStore.local_user.some((item: object) => item['_id'] === data['_id'])) {
      userStore.local_user.push({_id: data._id, avatar: data.avatar, account: data.account})
      localStorage.setItem('local_user', JSON.stringify(userStore.local_user))
    }


    await router.push('/home')
    // await router.push('/test')
    indexStore.init_socket({query: {user_id: userStore.user._id}})
    ElMessage({
      message: '登录成功',
      type: 'success',
      plain: true,
    })
  } else {
    ElMessage({
      message: '登录失败',
      type: 'error',
      plain: true,
    })
  }
}
// 注册
const on_register = async () => {
  const is_add = await userStore.on_register()
  if (is_add) {
    ElMessage({
      message: '注册成功',
      type: 'success',
      plain: true,
    })
    is_login.value = true
  } else {
    ElMessage({
      message: `注册失败`,
      type: 'error',
      plain: true,
    })
  }
}
// 样式更改为注册
const to_register = () => {
  is_login.value = false
}
// 样式更改为登录
const to_login = () => {
  is_login.value = true
}
// 去往重置密码页面
const to_resetPassword = () => {
  router.push('resetPassword')
}
</script>

<template>
  <div class="w-full h-svh flex justify-center items-center bg-blue-500">
    <div class="w-[220px] h-[300px] bg-blue-200">
      <div class="flex justify-center m-3 mt-5">
        <el-avatar :size="50" :src="userStore.user.avatar"/>
      </div>
      <el-form label-width="auto" :model="userStore.user" style="max-width: 600px" class="m-4" :rules="rules">
        <el-form-item prop="account">
          <el-input v-model="userStore.user.account" @input="getAvatar" placeholder="输入账户"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input show-password v-model="userStore.user.password" placeholder="输入密码"/>
        </el-form-item>
      </el-form>
      <div class="m-3">
        <el-button :disabled="btn" v-if="is_login" class="w-full" type="primary" @click="on_login">登录</el-button>
        <el-button :disabled="btn" v-else class="w-full" type="primary" @click="on_register">注册</el-button>
      </div>
      <div>
        <div class="flex justify-between m-10 text-[10px] text-blue-500">
          <div v-if="is_login" class="hover:text-blue-700 cursor-pointer" @click="to_register">注册账户</div>
          <div v-else class="hover:text-blue-700 cursor-pointer" @click="to_login">登录账户</div>
          <div class="hover:text-blue-700 cursor-pointer" @click="to_resetPassword">重置密码</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>